﻿using CCWin;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StudentSynchronization.Daemon
{
    public partial class FrmAdd : Skin_Color
    {
        private ProcessInfo proModel = null;
        public FrmAdd(ProcessInfo _proInfo)
        {
            proModel = _proInfo;
            InitializeComponent();
        }

        private void FrmAdd_Load(object sender, EventArgs e)
        {
            if (proModel == null)
            {
                this.Text = "添加新进程";
            }
            else
            {
                this.Text = "编辑进程信息";

                tbProName.Text = proModel.Name;
                tbProNameCn.Text = proModel.Desc;
                tbProPath.Text = proModel.Path;
            }
        }

        /// <summary>
        /// 新增 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(tbProName.Text)
                || string.IsNullOrWhiteSpace(tbProPath.Text)
                || string.IsNullOrWhiteSpace(tbProNameCn.Text))
            {
                MessageBox.Show("必填项不能为空，请输入。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (!File.Exists(tbProPath.Text + Path.DirectorySeparatorChar + tbProName.Text))
            {
                MessageBox.Show("当前文件不存在，请修改后重试。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            #region 杀原进程
            if (proModel != null)
            {
                var findpro = Process.GetProcessesByName(proModel.Name.Replace(".exe", "")).FirstOrDefault(p => p.MainModule.FileName == proModel.Path + Path.DirectorySeparatorChar + proModel.Name);
                if (findpro != null && findpro.Id > 0)
                {
                    findpro.Kill();
                    ProcessData.processlist[proModel.IndexNum].PID = "0";
                    ProcessData.processlist[proModel.IndexNum].IsDie = true;
                }
            }
            #endregion

            ProLogic.Instance.SyncAddEditToXml(tbProName.Text, tbProPath.Text, tbProNameCn.Text, proModel?.IndexNum);
            this.Close();
        }

        private void btnNo_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dia = new FolderBrowserDialog() { SelectedPath = tbProPath.Text };
            if (dia.ShowDialog() == DialogResult.OK)
            {
                tbProPath.Text = dia.SelectedPath;
            }
        }
    }
}
